<template>
  <doc-alert
    title="【库存】库存调拨、库存盘点"
    url="https://doc.iocoder.cn/erp/stock-move-check/"
  />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="盘点单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入盘点单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="盘点时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="deptId">
        <el-select
          v-model="queryParams.deptId"
          clearable
          filterable
          placeholder="请选择仓库"
          class="!w-240px"
        >
          <el-option
            v-for="item in deptList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建人" prop="creator">
        <el-select
          v-model="queryParams.creator"
          clearable
          filterable
          placeholder="请选择创建人"
          class="!w-240px"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getFilteredIntDictOptions(DICT_TYPE.APPROVE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column width="30" label="选择" type="selection" /> -->
      <el-table-column min-width="200" label="盘点单号" align="center" prop="no" />
      <el-table-column min-width="150" label="部门名称" align="center" prop="deptName" />
      <el-table-column
        label="盘点时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="220px"
      />
      <el-table-column min-width="100" label="盘点人" align="center" prop="creatorName" />
      <el-table-column label="流程实例的编号" align="center" prop="processInstanceId" v-if="false"/>
      <el-table-column min-width="100" label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.APPROVE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="220">
        <template #default="scope">
          <!-- <el-button
          type="primary"
          link
          @click="handleExport(scope.row.id)"
          :loading="exportLoading"
          v-hasPermi="['erp:stock-check:export']"
        >
          导出
        </el-button> -->
          <el-button
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
            v-hasPermi="['erp:stock-check:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('updateStatus', scope.row.id,scope.row.taskId)"
            v-hasPermi="['erp:stock-check:update-status']"
            v-if="scope.row.status === 1"
          >
            审批
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StockCheckForm ref="formRef" @success="getList()" />
  <!-- 表单弹窗：详情 -->
  <!-- <StockCheckForm ref="detailRef" @success="getList" :task-id="taskId" /> -->
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StockCheckApi, StockCheckVO } from '@/api/spd/hospitaloffice/stockcheck'
import StockCheckForm from './StockCheckForm1.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
// import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { DeptVO } from '@/api/system/dept'
import * as DeptApi from '@/api/system/dept'
// import { erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'

/** ERP 其它盘点单列表 */
defineOptions({ name: 'ErpStockCheck' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const deptList = ref<Tree[]>([]) // 树形结构
const loading = ref(true) // 列表的加载中
const list = ref<StockCheckVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  deptName :  undefined,
  no: undefined,
  productId: undefined,
  // warehouseId: undefined,
  createTime: [],
  status: undefined,
  remark: undefined,
  creator: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<ProductVO[]>([]) // 产品列表
// const deptList = ref<DeptVO[]>([]) // 仓库列表
const userList = ref<UserVO[]>([]) // 用户列表
const parentId = ref(100)
// let taskId = ref('')


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StockCheckApi.getStockCheckPageByStatus(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const getFilteredIntDictOptions = (dictType) => {
  const options = getIntDictOptions(dictType);
  return options.filter(option => [1, 2, 3].includes(option.value));
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number,taskId?: string) => {
  formRef.value.open(type, id, taskId)
}

// 详情弹窗
const detailRef = ref()
const openDetail = (type: string, id: number) => {
  // 获取list中跟id匹配的数据 并把taskId赋给taskId
  // taskId.value = list.value.find((item) => item.id === id)?.taskId
  detailRef.value.open(type, id)
}

/** 删除按钮操作 */
// const handleDelete = async (ids: number[]) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await StockCheckApi.deleteStockCheck(ids)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//     selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
//   } catch {}
// }

/** 审批/退回操作 */
const handleUpdateStatus = async (id: number, status: number) => {
  try {
    // 审批的二次确认
    await message.confirm(`确定${status === 3 ? '审批' : '退回'}该盘点单吗？`)
    // 发起审批
    await StockCheckApi.updateStockCheckStatus(id, status)
    message.success(`${status === 3 ? '审批' : '退回'}成功`)
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async (id: number) => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StockCheckApi.exportStockCheck(id)
    download.excel(data, '盘点单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// /** 选中操作 */
// const selectionList = ref<StockCheckVO[]>([])
// const handleSelectionChange = (rows: StockCheckVO[]) => {
//   selectionList.value = rows
// }

/** 初始化 **/
onMounted(async () => {
  // deptList.value = await DeptApi.getSimpleDeptList()
  deptList.value = handleTree(await DeptApi.getSimpleDeptLists(parentId.value))
  await getList()
  // 加载产品、仓库列表、客户
  productList.value = await ProductApi.getProductSimpleList()
  userList.value = await UserApi.getSimpleUserList()
})
// TODO 芋艿：可优化功能：列表界面，支持导入
// TODO 芋艿：可优化功能：详情界面，支持打印
</script>
